// utils/imageUtils.js - 图片资源统一管理工具
const config = require('./config.js');

/**
 * 获取图标资源的完整URL
 * @param {string} iconPath - 图标路径（如：'send.png', 'chat-active.png'）
 * @returns {string} 完整的图标URL
 */
function getIconUrl(iconPath) {
  // 去掉开头的斜杠（如果有的话）
  const cleanPath = iconPath.replace(/^\//, '');
  // 仅当配置显式开启时才优先走本地图标，默认走网络URL
  if (config.WECHAT_CONFIG && config.WECHAT_CONFIG.USE_LOCAL_ICONS === true) {
    const preferLocalIcons = new Set([
      'send.png',
      'three.png',
      'AIPortrait.png',
      'touxiang.png',
      'weixin.png',
      'img_bg.png'
    ]);
    if (preferLocalIcons.has(cleanPath)) {
      const localUrl = `/images/${cleanPath}`;
      console.log(`[getIconUrl] 使用本地图标优先: ${cleanPath} -> ${localUrl}`);
      return localUrl;
    }
  }
  const fullUrl = `${config.RESOURCE_CONFIG.ICON_BASE_URL}/${cleanPath}`;
  
  // 添加调试日志
  console.log(`[getIconUrl] 输入路径: ${iconPath}`);
  console.log(`[getIconUrl] 清理后路径: ${cleanPath}`);
  console.log(`[getIconUrl] ICON_BASE_URL: ${config.RESOURCE_CONFIG.ICON_BASE_URL}`);
  console.log(`[getIconUrl] 最终URL: ${fullUrl}`);
  
  return fullUrl;
}

/**
 * 获取图片资源的完整URL
 * @param {string} imagePath - 图片路径（如：'default-avatar.png', 'share-logo.png'）
 * @returns {string} 完整的图片URL
 */
function getImageUrl(imagePath) {
  // 去掉开头的斜杠（如果有的话）
  const cleanPath = imagePath.replace(/^\//, '');
  return `${config.RESOURCE_CONFIG.IMAGE_BASE_URL}/${cleanPath}`;
}

/**
 * 获取用户头像URL，支持自定义头像和默认头像
 * @param {string} avatarUrl - 用户自定义头像URL（可能为空）
 * @param {string} defaultAvatar - 默认头像路径（可选，默认使用touxiang.png）
 * @returns {string} 头像URL
 */
function getAvatarUrl(avatarUrl, defaultAvatar = 'touxiang.png') {
  if (avatarUrl && avatarUrl.trim()) {
    return avatarUrl;
  }
  return getIconUrl(defaultAvatar);
}

/**
 * 资源路径映射表 - 将旧的本地路径映射到新的资源路径
 */
const RESOURCE_MAP = {
  // 图标资源（移到后端/icons/）
  '/images/send.png': () => getIconUrl('send.png'),
  '/images/three.png': () => getIconUrl('three.png'),
  '/images/copy.png': () => getIconUrl('copy.png'),
  '/images/jifen.png': () => getIconUrl('jifen.png'),
  '/images/touxiang.png': () => getIconUrl('touxiang.png'),
  '/images/weixin.png': () => getIconUrl('weixin.png'),
  '/images/AIPortrait.png': () => getIconUrl('AIPortrait.png'),
  
  // 底部导航图标
  'images/chat.png': () => getIconUrl('chat.png'),
  'images/chat-active.png': () => getIconUrl('chat-active.png'),
  'images/ai-image-gen.png': () => getIconUrl('ai-image-gen.png'),
  'images/ai-image-gen-active.png': () => getIconUrl('ai-image-gen-active.png'),
  'images/assistant.png': () => getIconUrl('assistant.png'),
  'images/assistant-active.png': () => getIconUrl('assistant-active.png'),
  'images/profile.png': () => getIconUrl('profile.png'),
  'images/profile-active.png': () => getIconUrl('profile-active.png'),
  
  // 其他图片资源
  '../../images/img_bg.png': () => getIconUrl('img_bg.png'),
  
  // 图片资源（保留在后端/images/）
  '/images/default-avatar.png': () => getImageUrl('default-avatar.png'),
  '/images/share-logo.png': () => getImageUrl('share-logo.png'),
  '/images/share-timeline.png': () => getImageUrl('share-timeline.png'),
  '/images/vip-share.png': () => getImageUrl('vip-share.png'),
  '/images/vip-timeline.png': () => getImageUrl('vip-timeline.png'),
  '/images/credits-share.png': () => getImageUrl('credits-share.png'),
  '/images/credits-timeline.png': () => getImageUrl('credits-timeline.png'),
  '/images/share-assistant.png': () => getImageUrl('share-assistant.png'),
  '/images/share-category.png': () => getImageUrl('share-category.png')
};

/**
 * 解析资源路径，自动映射到正确的后端URL
 * @param {string} resourcePath - 原始资源路径
 * @returns {string} 解析后的完整URL
 */
function resolveResourceUrl(resourcePath) {
  const mapper = RESOURCE_MAP[resourcePath];
  if (mapper) {
    return mapper();
  }
  
  // 如果没有找到映射，尝试智能判断
  if (resourcePath.includes('images/') && !resourcePath.startsWith('http')) {
    // 提取文件名
    const fileName = resourcePath.split('/').pop();
    
    // 根据文件名判断是图标还是图片
    const iconFiles = ['send.png', 'three.png', 'copy.png', 'jifen.png', 'touxiang.png', 'weixin.png', 'AIPortrait.png', 'img_bg.png',
                      'chat.png', 'chat-active.png', 'ai-image-gen.png', 'ai-image-gen-active.png', 
                      'assistant.png', 'assistant-active.png', 'profile.png', 'profile-active.png'];
    
    if (iconFiles.includes(fileName)) {
      return getIconUrl(fileName);
    } else {
      return getImageUrl(fileName);
    }
  }
  
  // 如果都不匹配，返回原路径
  return resourcePath;
}

module.exports = {
  getIconUrl,
  getImageUrl,
  getAvatarUrl,
  resolveResourceUrl,
  RESOURCE_MAP
};
